﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
using JQueryControlToolkit;

namespace JQueryControlToolkit.Sample.Web.Samples
{
    public partial class SourceCode : System.Web.UI.UserControl
    {
        public string SourcePage { get; set; }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            JQueryControlToolkit.JQuery jquery = new JQueryControlToolkit.JQuery("#viewSource").Click(new JQueryControlToolkit.JQuery("#" + src.ClientID).Toggle(ToggleEffect.Blind));
            JQueryControlToolkit.JQueryPageExtensions.Add(Page, jquery);
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            EnsureChildControls();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public override void DataBind()
        {
            base.DataBind();
            int questionMarkIndex = SourcePage.IndexOf('?');
            string filePath = Server.MapPath("~" + SourcePage.Substring(SourcePage.IndexOf("/Samples"), (questionMarkIndex > 0 ? questionMarkIndex : SourcePage.Length) - SourcePage.IndexOf("/Samples")));
            Visible = File.Exists(filePath);
            if (Visible)
            {
                string fileContent = File.ReadAllText(filePath);
                string usefulContent = new Regex(@"<asp:Content ([^C]|C[^o]|Co[^n]|Con[^t]|Cont[^e]|Conte[^n]|Conten[^t]|Content[^P]|ContentP[^l]|ContentPl[^a]|ContentPla[^c]|ContentPlac[^e]|ContentPlace[^H]|ContentPlaceH[^o]|ContentPlaceHo[^l]|ContentPlaceHol[^d]|ContentPlaceHold[^e]|ContentPlaceHolde[^r]|ContentPlaceHolder[^I]|ContentPlaceHolderI[^D]|ContentPlaceHolderID[^=])+ContentPlaceHolderID=[""']body[""'][^>]*>(?<source>([^<]|<[^/]|</[^:]+>|</[^:]+:([^C]|C[^o]|Co[^n]|Con[^t]|Cont[^e]|Conte[^n]|Conten[^t]|Content[^>]+)+>)*)</asp:Content>").Match(fileContent).Groups["source"].Value.Replace(">", "&gt;").Replace("<", "&lt;");
                usefulContent = usefulContent.Replace(Environment.NewLine, "<br />" + Environment.NewLine);
                usefulContent = usefulContent.Replace("\t", "&nbsp;&nbsp;");
                usefulContent = usefulContent.Replace("    ", "&nbsp;&nbsp;");
                usefulContent = usefulContent.Replace("  ", "&nbsp;&nbsp;");
                src.Controls.Add(new Literal() { Text = usefulContent });
            }
        }
    }
}